package com.msmall.base.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class FileIO {

	private static final Log logger = LogFactory.getLog(FileIO.class);

	public static String readFile(String filePath) {
		return readFile(filePath,Constants.DEFAULT_CHARSET);
	}

	public static String readFile(String filePath, String charset) {
		String info = "";
		try {
			File f = new File(filePath);
			if (f.exists()) {
				FileInputStream bw = new FileInputStream(f);
				int len = bw.available();
				byte[] str = new byte[len];
				if (bw.read(str) == -1) {
					info = "";
				} else {
					info = new String(str, charset);
				}
				bw.close();
				bw = null;
			}
			f = null;
		} catch (IOException e) {
			logger.error(e);
		}
		return info;
	}

	public static void writeFile(String msg, String filePath) throws IOException  {
		writeFile(msg, filePath, Constants.DEFAULT_CHARSET);
	}

	public static void writeFile(String msg, String filePath, String charset) throws IOException {
		try{
			File file = new File(filePath);
			if (file.exists()) {
				file.delete();
			}
			FileUtils.writeStringToFile(file, msg, charset);
			file = null;
		} catch (IOException e) {
			logger.error(e);
			throw e;
		} finally {
		}
	}
	

	public static String getRandomFileName(){
		RandomGUID rand = new RandomGUID();
		String fileName = rand.toString();
		rand = null;
		return fileName;
	}
	
	public static void deleteFile(String filePath){
		try {
			File file = new File(filePath);
			FileUtils.forceDelete(file);
		} catch (IOException e) {
			logger.error(e);
		}
	}
	
	public static File getUniqueFile(final File file) {
		if (!file.exists())
			return file;

		File tmpFile = new File(file.getAbsolutePath());
		File parentDir = tmpFile.getParentFile();
		int count = 1;
		String extension = FilenameUtils.getExtension(tmpFile.getName());
		String baseName = FilenameUtils.getBaseName(tmpFile.getName());
		do {
			tmpFile = new File(parentDir, baseName + "(" + count++ + ")."
					+ extension);
		} while (tmpFile.exists());
		return tmpFile;
	}
}
